get-stack-trace
V8 stack traces with optional source map resolution.
Motivation
A lot of NPM packages are transpiled either using Babel or TypeScript.
This means that if you attempt to resolve a CallSite using Error.prepareStackTrace
and Error.captureStackTrace
, the resulting CallSite object will reference the tranpiled file, rather than the original source file. However, if the project was distributed with source maps, then we can use the available source maps to resolve the original CallSite.
In practise, this is useful if the intent is to log the stack trace of an application at a particular time in execution, e.g. Slonik creates a stack trace prior to every asynchronous call for debugging purposes.
For the stack traces to resolve, packages must be distributed with a source map file along with the transpiled file, e.g. such as in the case of this project:
$ cd ./dist && tree .
.
├── index.js
├── index.js.flow
├── index.js.map
├── test.js
├── test.js.flow
├── test.js.map
├── types.js
├── types.js.flow
└── types.js.map
Types
type CallSiteType = {|
+getColumnNumber: () => number,
+getEvalOrigin: () => string,
+getFileName: () => Function | void,
+getFunction: () => string | void,
+getFunctionName: () => string,
+getLineNumber: () => number,
+getMethodName: () => string,
+getThis: () => Object | void,
+getTypeName: () => string,
+isConstructor: () => boolean,
+isEval: () => boolean,
+isNative: () => boolean,
+isToplevel: () => boolean
|};
type NormalisedCallSiteType = {|
+columnNumber: string,
+fileName: string,
+lineNumber: string
|};
type ResolvedCallSiteType = {|
+callSite: CallSiteType,
+originalNormalisedCallSite: NormalisedCallSiteType,
+reportedNormalisedCallSite: NormalisedCallSiteType
|};
declare function getStackTrace (): $ReadOnlyArray<CallSiteType>;
declare function getOriginalStackTrace (): Promise<$ReadOnlyArray<ResolvedCallSiteType>>;
Usage
import {
getOriginalStackTrace,
getStackTrace
} from 'get-stack-trace';
const traces = await getOriginalStackTrace(getStackTrace());